/*
 * Programmer: Abubakr
 * Date Modified: February 9, 2010
 * Description: Very simple Tic Tac Toe game.
 */
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Main implements ActionListener {

	private int[][] winPossibilites = new int[][] { { 0, 1, 2 }, { 3, 4, 5 },
			{ 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 },
			{ 2, 4, 6 } };
	private int move;
	private JButton[] box = new JButton[9];
	private JFrame window;
	private String text = "X";

	public Main() {
		// Create window
		window = new JFrame();
		window.setSize(400, 400);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setVisible(true);
		window.setLayout(new GridLayout(3, 3));

		// Create and add buttons to window.
		for (int i = 0; i < 9; i++) {
			box[i] = new JButton();
			window.add(box[i]);
			box[i].addActionListener(this);
		}
		window.validate();
		if (((int) (Math.random() * 3)) == 2) {
			AITurn();
		}
	}

	public void AITurn() {
		// First check if possible win.
		if (possibleWin()) {
			box[move].setText(text);
			box[move].setEnabled(false);
		}
	}

	public boolean possibleWin() {
		// If can win horizontally.
		for (int i = 0; i <= 6; i += 3){
			if (box[i].getText().equals(text) && box[i + 1].getText().equals(text) && box[i + 3].getText().equals("")){
				move = i + 3;
			}
		}		
		// If can win vertically.
		
		return false;
	}

	public static void main(String[] args) {
		new Main();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// For whichever button is clicked, change its text based on current
		// turn.
		JButton buttonClicked = (JButton) arg0.getSource();
		buttonClicked.setText(text);
		buttonClicked.setEnabled(false);
		checkWin();
		// Next turn
		if (text.equals("X")) {
			text = "O";
		} else {
			text = "X";
		}
		AITurn();
		

	}

	public void checkWin() {
		for (int i = 0; i < 8; i++) {
			if (box[winPossibilites[i][0]].getText().equals(
					box[winPossibilites[i][1]].getText())
					&& box[winPossibilites[i][1]].getText().equals(
							box[winPossibilites[i][2]].getText())
					&& !box[winPossibilites[i][0]].getText().equals("")) {
				JOptionPane.showMessageDialog(null, text + " wins!");
				window.dispose();
			}
		}
	}
}
